package com.bnyy.medicalHousekeeper.activity;


import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;

import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SpanUtils;
import com.bnyy.medicalHousekeeper.BuildConfig;
import com.bnyy.medicalHousekeeper.DialogHelper;
import com.bnyy.medicalHousekeeper.GlideHelper;
import com.bnyy.medicalHousekeeper.R;
import com.bnyy.medicalHousekeeper.base.App;
import com.bnyy.medicalHousekeeper.base.BaseActivityImpl;
import com.bnyy.medicalHousekeeper.bean.User;
import com.bnyy.medicalHousekeeper.request.BaseObserverImpl;
import com.bnyy.medicalHousekeeper.request.RequestManager;
import com.bnyy.common.Constant;
import com.just.agentweb.AgentWeb;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

//import android.app.AlertDialog;

public class LoginActivity extends BaseActivityImpl implements BaseActivityImpl.UnnecessaryRequestGlobalParams, BaseActivityImpl.UnnecessaryLogin {

    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.cb_login)
    CheckBox cbLogin;
    @BindView(R.id.tv_agreement)
    TextView tvAgreement;
    @BindView(R.id.iv_logo)
    ImageView ivLogo;
    @BindView(R.id.tv_get_code)
    TextView tvGetCode;
    @BindView(R.id.tv_no_code)
    TextView tvNoCode;
    @BindView(R.id.tv_login)
    TextView tvLogin;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.ll_web)
    LinearLayout llWeb;

    private SharedPreferences sp;
    private long lastClick = 0;
    private int clickToSwitchServe = 0;


    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public String getTitleStr() {
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 华为首次启动webview后会导致传入的上下文activity重启，具体原因未知，
        // 在启动页启动一次webview以避免
        AgentWeb.with(this)//传入Activity
                .setAgentWebParent(llWeb, new LinearLayout.LayoutParams(1, 1))//传入AgentWeb 的父控件 ，如果父控件为 RelativeLayout ， 那么第二参数需要传入 RelativeLayout.LayoutParams
                .useDefaultIndicator()// 使用默认进度条
                .createAgentWeb()//
                .ready()
                .go("");

//        initData();

        SpanUtils.with(tvAgreement)
                .append("我已阅读并同意")
                .append("《" + getResources().getString(R.string.app_name) + "APP用户协议协议》")
                .setClickSpan(ContextCompat.getColor(mContext, R.color.green_theme), false, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        WebViewActivity.show(mContext, requestManager.getBaseUrl() + Constant.NetWork.URL_AGREEMENT);
                    }
                })
                .append("和")
                .append("《隐私协议》")
                .setClickSpan(ContextCompat.getColor(mContext, R.color.green_theme), false, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        WebViewActivity.show(mContext, requestManager.getBaseUrl() + Constant.NetWork.URL_PRIVACY_RIGHTS);
                    }
                })
                .create();

        sp = getSharedPreferences(Constant.SP_NAME, MODE_PRIVATE);
        int version = sp.getInt(Constant.SpTag.SHOW_AGREEMENT_DIALOG, -1);
        if (version < BuildConfig.VERSION_CODE) {
            showAgreementDialog();
        }
//        else {
//            requestGlobalParams();
//        }
        GlideHelper.setRoundImage(mContext, R.mipmap.icon_logo_yygj, ivLogo);
        ivLogo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long currentTimeMillis = System.currentTimeMillis();
                if (currentTimeMillis - lastClick <= 1000) {
                    lastClick = currentTimeMillis;
                    clickToSwitchServe++;
                    if (clickToSwitchServe == 9) {
                        String content = "当前服务器：\n" + requestManager.getBaseUrl();
                        DialogHelper.showNormalDialog(mContext, "请选择服务器", content, "测试环境", "正式环境",
                                new DialogHelper.Callback() {
                                    @Override
                                    public void onLeftClick(AlertDialog alertDialog) {
                                        requestManager.initBaseUrl(Constant.NetWork.BASE_URL_TEST);
                                    }

                                    @Override
                                    public void onRightClick(AlertDialog alertDialog) {
                                        requestManager.initBaseUrl(Constant.NetWork.BASE_URL_FORMAL);
                                    }
                                });
                        clickToSwitchServe = 0;
                    }
                } else {
                    lastClick = currentTimeMillis;
                    clickToSwitchServe = 0;
                    clickToSwitchServe++;
                }
            }
        });
    }

    public void initData() {
        //        输入手机号
        String a = "我已阅读并同意";
        String b = "《" + getResources().getString(R.string.app_name) + "APP用户协议协议》";
        String c = "和";
        String d = "《隐私协议》";

        SpannableStringBuilder style = new SpannableStringBuilder();
        //设置文字
        style.append(a).append(b).append(c).append(d);
        // 设置部分文字点击事件
        ClickableSpan clickableSpanAgreement = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                WebViewActivity.show(mContext, requestManager.getBaseUrl() + Constant.NetWork.URL_AGREEMENT);
            }
        };
        style.setSpan(clickableSpanAgreement, a.length(), a.length() + b.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        ClickableSpan clickableSpanPrivacyRights = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                WebViewActivity.show(mContext, requestManager.getBaseUrl() + Constant.NetWork.URL_PRIVACY_RIGHTS);
            }
        };
        style.setSpan(clickableSpanPrivacyRights, a.length() + b.length() + c.length(),
                a.length() + b.length() + c.length() + d.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        // 设置部分文字颜色
        style.setSpan(new ForegroundColorSpan(Color.parseColor("#21AB38")), a.length(),
                a.length() + b.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        style.setSpan(new ForegroundColorSpan(Color.parseColor("#21AB38")), a.length() + b.length() + c.length(),
                a.length() + b.length() + c.length() + d.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        tvAgreement.setMovementMethod(LinkMovementMethod.getInstance());
        tvAgreement.setText(style);
    }

    Timer timer;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
    }

    private void getCode() {
        String phone = etPhone.getText().toString();
        if (TextUtils.isEmpty(etPhone.getText()) || etPhone.getText().length() != 11) {
            Toast.makeText(mContext, "请输入正确的手机号码", Toast.LENGTH_SHORT).show();
        } else {
            HashMap<String, Object> params = new HashMap<>();
            params.put("phone", phone);
            requestManager.request(requestManager.mJavaRetrofitService.getCode(RequestManager.getJsonRequestBody(params)),
                    new BaseObserverImpl<Object>(mContext) {
                        @Override
                        public void onSuccess(Object o) {
                            super.onSuccess(o);
                            Toast.makeText(mContext, "验证码已发送", Toast.LENGTH_SHORT).show();
                            tvLogin.setTag(phone);

                            tvGetCode.setTag(60);
                            tvGetCode.setEnabled(false);
                            new CountDownTimer(60, 1000) {
                                @Override
                                public void onTick(long millisUntilFinished) {

                                }

                                @Override
                                public void onFinish() {

                                }
                            }.start();
                            timer = new Timer();
                            timer.schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            int tag = (int) tvGetCode.getTag();

                                            tvGetCode.setText(tag + "s");
                                            tag -= 1;
                                            if (tag == 0) {
                                                tvGetCode.setEnabled(true);
                                                tvGetCode.setText("发送验证码");
                                                cancel();
                                            } else {
                                                tvGetCode.setTag(tag);
                                            }
                                        }
                                    });
                                }
                            }, 0, 1000);
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);
                            Toast.makeText(mContext, "获取验证码失败", Toast.LENGTH_SHORT).show();
                        }
                    });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 1) {
            startActivity(data);
            finish();
        }
    }

    private void showAgreementDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

        View view = inflater.inflate(R.layout.dialog_agreement, null);
        TextView tvAgreement = view.findViewById(R.id.tv_agreement);
        TextView tvLeft = view.findViewById(R.id.tv_left);
        TextView tvRight = view.findViewById(R.id.tv_right);

        AlertDialog alertDialog = builder.setCancelable(false).setView(view).create();

        final SpannableStringBuilder style = new SpannableStringBuilder();

        String a = "为了更好地保护您的权益，同时遵守相关监管要求，我们更新了";
        String b = "《" + getResources().getString(R.string.app_name) + "APP用户协议》";
        String c = "和";
        String d = "《隐私协议》";
        String e = "特向您说明如下：";

        //设置文字
        style.append(a)
                .append(b)
                .append(c)
                .append(d)
                .append(e);

        // 设置部分文字点击事件
        ClickableSpan clickableSpanAgreement = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                WebViewActivity.show(mContext, requestManager.getBaseUrl() + Constant.NetWork.URL_AGREEMENT);
            }
        };
        style.setSpan(clickableSpanAgreement, a.length(), a.length() + b.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        ClickableSpan clickableSpanPrivacyRights = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                WebViewActivity.show(mContext, requestManager.getBaseUrl() + Constant.NetWork.URL_PRIVACY_RIGHTS);
            }
        };
        style.setSpan(clickableSpanPrivacyRights, a.length() + b.length() + c.length(),
                a.length() + b.length() + c.length() + d.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        // 设置部分文字颜色
        style.setSpan(new ForegroundColorSpan(Color.parseColor("#21AB38")), a.length(),
                a.length() + b.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        style.setSpan(new ForegroundColorSpan(Color.parseColor("#21AB38")), a.length() + b.length() + c.length(),
                a.length() + b.length() + c.length() + d.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        tvAgreement.setMovementMethod(LinkMovementMethod.getInstance());
        tvAgreement.setText(style);

        tvLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                finish();
            }
        });
        tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sp.edit().putInt(Constant.SpTag.SHOW_AGREEMENT_DIALOG, BuildConfig.VERSION_CODE).apply();
//                requestGlobalParams();
                alertDialog.dismiss();
            }
        });
        alertDialog.show();

        Window window = alertDialog.getWindow();
        window.setBackgroundDrawableResource(android.R.color.transparent);
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.width = ScreenUtils.getScreenWidth() / 5 * 4;
        window.setAttributes(attributes);
    }

    @OnClick({R.id.tv_get_code, R.id.tv_no_code, R.id.tv_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_get_code:
                getCode();
                break;
            case R.id.tv_no_code:
                StringBuilder sb = new StringBuilder();
                sb.append("1.请确认手机号是否为当前使用的手机号")
                        .append("\n")
                        .append("2.请检查短信是否被安全软件拦截")
                        .append("\n")
                        .append("3.运营网络原因，短信可能延迟到达");
                DialogHelper.showTipsDialog(mContext, "没有收到验证码", sb);
                break;
            case R.id.tv_login:
                Editable text = etCode.getText();
                if (TextUtils.isEmpty(text) || text.length() != 4) {
                    Toast.makeText(mContext, "请输入正确的验证码", Toast.LENGTH_SHORT).show();
                } else {
                    if (!cbLogin.isChecked()) {
                        Toast.makeText(mContext, "请先阅读并同意《" + getResources().getString(R.string.app_name) + "APP用户协议协议》和《隐私协议》", Toast.LENGTH_SHORT).show();
                    } else {
                        HashMap<String, Object> params = new HashMap<>();
                        params.put("phone", view.getTag());
                        params.put("code", text.toString());
                        params.put("role_id", 4);
                        requestManager.request(requestManager.mJavaRetrofitService.login(RequestManager.getJsonRequestBody(params)),
                                new BaseObserverImpl<User>() {
                                    @Override
                                    public void onSuccess(User user) {
                                        super.onSuccess(user);

                                        App.setUser(user);
                                        RequestManager.setToken(user.getSid());

                                        BaseActivityImpl.show(mContext, MainActivity.class);
                                        finish();
                                    }
                                });
                    }
                }
                break;
        }
    }
}





























